﻿using System.Text.RegularExpressions;
using System.Net;
using System.Web.UI;
using System.Web;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Text;
using System.Xml;


namespace Designit.Umb.DataTypes.Video
{
    public class XsltExtension
    {
        private enum VideoType {
            YouTube,
            Google,
            Vimeo,
            NoneExisting
        }
        public static string VideoEmbed(string url, int height, int width)
        {
            VideoType videoType;
            string videoId;
            var videoUrl = GetVideoUrl(url, out videoType, out videoId);
            return videoType == VideoType.NoneExisting ? "<b>ERROR:</b> video format not supported" : VideoEmbedParameters(videoUrl, height, width);
        }

        public static string VideoEmbedInLightBox(string url, int height, int width, int previewHeight, int previewWidth)
        {
            VideoType videoType;
            string videoId;
            var videoUrl = GetVideoUrl(url, out videoType, out videoId);

            if (videoType == VideoType.Google)
                return "<b>ERROR: Google Video is not supported by lightbox integration.</b><br />Please use another video format.";

            var page = HttpContext.Current.Handler as Page;
            if(page != null)
            {
                umbraco.library.RegisterJavaScriptFile("fancybox", "/scripts/Designit.VideoEmbed/jquery.fancybox-1.3.1.pack.js");
                umbraco.library.RegisterStyleSheetFile("cssFancyBox", "/css/Designit.VideoEmbed/jquery.fancybox-1.3.1.css");
                umbraco.library.RegisterJavaScriptFile("jsDesignitVideoEmbed", "/scripts/Designit.VideoEmbed/FancyBoxInit.js");
                umbraco.library.RegisterStyleSheetFile("cssDesignitVideoEmbed", "/css/Designit.VideoEmbed/screen.css");
            }

            var thumbUrl = string.Empty;
				var videoTitle = string.Empty;
            if(videoType == VideoType.YouTube)
            {
                thumbUrl = "http://i.ytimg.com/vi/" + videoId + "/default.jpg";
                if (previewWidth > 120 || previewHeight > 90)
                {
                    //var webRequest = WebRequest.Create("http://i.ytimg.com/vi/" + videoId + "/hqdefault.jpg");
                    //var webResponse = (HttpWebResponse) webRequest.GetResponse();
                    //if (webResponse.StatusCode == HttpStatusCode.OK)
                        thumbUrl = "http://i.ytimg.com/vi/" + videoId + "/hqdefault.jpg";
                }
            }
            else if (videoType == VideoType.Vimeo)
            {
                var webRequest = WebRequest.Create(string.Format("http://vimeo.com/api/v2/video/{0}.xml", videoId));
                var webResponse = webRequest.GetResponse();
                var xmlDoc = new XmlDocument();
                XmlNode node = null;
                xmlDoc.Load(webResponse.GetResponseStream());
                if(previewWidth <= 100)
                {
                    node = xmlDoc.SelectSingleNode(@"videos/video/thumbnail_small");
                }
                else if(previewWidth <= 200)
                {
                    node = xmlDoc.SelectSingleNode(@"videos/video/thumbnail_medium");
                }
                else
                {
                    node = xmlDoc.SelectSingleNode(@"videos/video/thumbnail_large");
                }
                if (node != null)
                {
                    if(!string.IsNullOrEmpty(node.InnerText))
                        thumbUrl = node.InnerText;
                }

					 if (xmlDoc.SelectSingleNode(@"videos/video/title") != null && !string.IsNullOrEmpty(xmlDoc.SelectSingleNode(@"videos/video/title").InnerText))
					 {
						 videoTitle = xmlDoc.SelectSingleNode(@"videos/video/title").InnerText;
					 } 

            }

            return videoType == VideoType.NoneExisting
                       ? "<b>ERROR:</b> video format not supported"
							  : string.Format(@"<div class=""videoPreview""><a href=""{0}&amp;autoplay=1"" id=""id_{4}"" class=""videoEmbedFancy"" onclick=""openFancyBoxVideo(this, {5}, {6});return false;""><span></span><img src=""{1}"" width=""{2}"" height=""{3}"" alt=""{7}"" /></a></div>", videoUrl, thumbUrl, previewWidth, previewHeight, videoId, width, height, videoTitle);
        }


        private static string VideoEmbedParameters(string url, int height, int width)
        {
            return "<object width=\"" + width + "\" height=\"" + height + "\"><param name=\"movie\" value=\"" + url +
                   "\"></param><param name=\"allowFullScreen\" value=\"true\"></param><param name=\"allowscriptaccess\" value=\"always\"></param><embed src=\"" +
                   url + "\" type=\"application/x-shockwave-flash\" allowscriptaccess=\"always\" allowfullscreen=\"true\" width=\"" +
                   width + "\" height=\"" + height + "\"></embed></object>";
        }

        private static string GetVideoUrl(string url, out VideoType videoType, out string videoId)
        {
            var youTubeUrl = new Regex(@"^http://(www\.)?youtube.com/watch\?v=(?<id>[0-9A-Za-z-_]{11})$*");
            var vimeoUrl = new Regex(@"^http://(?:www\.){0,1}vimeo\.com/(\d+)$*");
            var googleVideoUrl = new Regex(@"^http://?video.google.com/videoplay\?docid=(?<id>[0-9A-Za-z-_]{19})$*");

            var urlNew = string.Empty;
            videoType = VideoType.NoneExisting;
            videoId = string.Empty;

            if (youTubeUrl.IsMatch(url))
            {
                var yid = youTubeUrl.Match(url).Groups["id"];
                urlNew = string.Format("http://www.youtube.com/v/{0}", yid.Value);
                videoId = yid.Value;
                videoType = VideoType.YouTube;
            }
            else if (vimeoUrl.IsMatch(url))
            {
                var vid = vimeoUrl.Match(url).Groups[1];
                urlNew = string.Format("http://vimeo.com/moogaloop.swf?clip_id={0}", vid.Value);
                videoId = vid.Value;
                videoType = VideoType.Vimeo;
            }
            else if (googleVideoUrl.IsMatch(url))
            {
                var gid = googleVideoUrl.Match(url).Groups["id"];
                urlNew = string.Format("http://video.google.com/googleplayer.swf?docId={0}", gid.Value);
                videoId = gid.Value;
                videoType = VideoType.Google;
            }

            return urlNew;
        }
    }
}